package language.advanced.Concurrent;

import java.util.ArrayList;
import java.util.List;
 
public class myBlockingQueqe<T> {
    //默认阻塞队列容量
    private int DEFAULT_CAPACITY = 3;
    private List<T> list;
 
    /**
     * 无惨构造
     * 使用默认容量初始化队列
     */
    public myBlockingQueqe() {
        list = new ArrayList<>(DEFAULT_CAPACITY);
    }
 
    /**
     * 有参构造
     * 自定义队列容量
     */
    public myBlockingQueqe(int capacity) throws Exception {
        DEFAULT_CAPACITY = capacity;
        list = new ArrayList<>(capacity);
    }
 
    /**
     * 阻塞放
     */
    public synchronized void put(T t) {
            while (list.size() == DEFAULT_CAPACITY) {
                try {
                    //等待
                    this.wait();
                } catch (InterruptedException e) {
                    System.out.println("put error!");
                }
            }
            //队列中元素个数少于队列容量时唤醒
            if (list.size() < DEFAULT_CAPACITY) {
                //唤醒
                this.notify();
            }
            list.add(t);
    }
 
    /**
     * 阻塞取
     */
    public synchronized T take() {
            while (list.size() == 0) {
                try {
                    //等待
                    this.wait();  //可能存在多个消费者阻塞在该wait上，所以要用while
                } catch (InterruptedException e) {
                    System.out.println("take error!");
                }
            }
            //队列中元素个数大于0时唤醒
            if (list.size() > 0) {
                //唤醒
                this.notify();
            }
            return list.remove(0);
    }
}